package com.flyxiaozhu.rabbitmqdemo;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
public class SendController {

    //  ---------------- direct 形式 -------------------
    @Autowired
    private AmqpTemplate amqpTemplate;

    @RequestMapping("/direct/send")
    public String directSend() {
        String content = "Date:" + new Date();
        amqpTemplate.convertAndSend("direct-queue-1", content);
        return content;
    }

    @RequestMapping("/direct/send2")
    public String directSend2() {
        String content = "Date:" + new Date();
        amqpTemplate.convertAndSend("direct-queue-2", content);
        return content;
    }

    @RequestMapping("/direct/multiSend")
    public String directMultiSend() {
        StringBuilder times = new StringBuilder();
        for (int i = 1; i <= 10; i++) {
            long time = System.nanoTime();
            amqpTemplate.convertAndSend("direct-queue-1", "第" + i + "次发送的信息：" + time);
            amqpTemplate.convertAndSend("direct-queue-2", "第" + i + "次发送的信息：" + time);
            times.append(time + "<br />");
        }
        return times.toString();
    }

    //  ---------------- fanout 形式 -------------------

    @Autowired
    private FanoutExchange fanoutExchange;

    @RequestMapping("/fanout/send")
    public String fanoutSend() {
        StringBuilder times = new StringBuilder();
        for (int i = 1; i <= 10; i++) {
            long time = System.nanoTime();
            amqpTemplate.convertAndSend(fanoutExchange.getName(), "", "第" + i + "次发送的信息：" + time);
            times.append(time + "<br />");
        }
        return times.toString();
    }

    //  ---------------- topic 形式 -------------------
    @RequestMapping("/topic/send")
    public String topicSend() {
        StringBuilder times = new StringBuilder();
        for (int i = 1; i <= 10; i++) {
            long time = System.nanoTime();
            amqpTemplate.convertAndSend("topic-exchange", "topic.queue-2", "第" + i + "次发送的信息：" + time);
            times.append(time + "<br />");
        }
        return times.toString();
    }

    @RequestMapping("/test/confirm")
    public void confirm() {
        amqpTemplate.convertAndSend("test", "test-queue", "这是消息内容哦！！！");
    }
}
